﻿Imports Models.Security
Imports Models.Users

Namespace Security

    Public Class Rols
        Private rolList As Generic.List(Of RolVO)

        Sub New()
            rolList = New Generic.List(Of RolVO)

            Dim defaultCompany As New CompanyVO()
            defaultCompany.code = "PUBLIC"

            Dim vo As New RolVO()

            vo.code = "public_user"
            vo.name = "Public User"
            vo.company = defaultCompany

            rolList.Add(vo)
        End Sub

        ''' <summary>
        ''' Sincronize rols and permisions
        ''' </summary>
        ''' <remarks></remarks>
        Public Sub sincronize()

            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")


                '' add/update all rols
                Dim dbRolList As Generic.List(Of Data.BaseModel.Rol) = (From r In oDB.Rols Select r).ToList
                Dim found As Boolean
                For Each rol As RolVO In rolList

                    found = False

                    '' locate rol in db
                    For Each dbRol As Data.BaseModel.Rol In dbRolList
                        If dbRol.Code = rol.code Then
                            dbRol.Name = rol.name
                            dbRol.System = True
                            found = True
                        End If
                    Next

                    '' create if not found
                    If Not found Then
                        Dim entity As New Data.BaseModel.Rol()

                        entity.Name = rol.name
                        entity.Code = rol.code
                        entity.System = True

                        'get company from code
                        entity.CompanyId = (From c In oDB.Companies Where c.Code = rol.company.code Select c.CompanyId).FirstOrDefault

                        oDB.Rols.AddObject(entity)
                    End If
                Next

                oDB.SaveChanges()

            End Using
        End Sub

    End Class
End Namespace